package com.gree.shyun.server.db.sqlite;

import com.gree.shyun.server.db.util.LogUtils;
import com.gree.shyun.server.db.util.SqlUtil;
import com.gree.shyun.server.db.util.TextUtils;

import java.sql.*;

/**
 * 数据库核心操作
 */
public class DataBase {
    private static DataBase su;
    private Connection conn = null;

    /**
     *
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    private DataBase(String dbName) throws ClassNotFoundException, SQLException {
        Class.forName("org.sqlite.JDBC");
        conn = DriverManager
                .getConnection("jdbc:sqlite:"+ DataBase.class.getClassLoader()
                        .getResource("").getPath().substring(1)+dbName);
        conn.setAutoCommit(false);
    }

    /**
     *
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public static DataBase getInstance(String dbName) throws ClassNotFoundException, SQLException {
        if (null == su) {
            su = new DataBase(dbName);
            return su;
        } else {
            return su;
        }
    }

    /**
     * 查询
     * @param sql
     * @return
     */
    public ResultSet rawQuery(String sql){
        return rawQuery(sql,null);
    }
    public ResultSet rawQuery(String sql,String[] args){
        if(args!=null){
            sql = SqlUtil.replaceSql(sql,args);
        }
        if(TextUtils.isEmpty(sql)){
            return null;
        }
        //LogUtils.e("rawQuery:"+sql);
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            return  ps.executeQuery();
        } catch (SQLException e) {
            LogUtils.e( "执行出错了",e);
        }
        return null;
    }

    /**
     * 更新
     * @param sql
     * @return
     */
    public Integer execSQL(String sql) {
        return execSQL(sql,null);
    }
    public Integer execSQL(String sql,Object[] objs) {
        if(objs!=null){
           sql = SqlUtil.replaceSql(sql,objs);
        }
        if(TextUtils.isEmpty(sql)){
            return null;
        }
        //LogUtils.e("execSQL:"+sql);
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            return  ps.executeUpdate();
        } catch (SQLException e) {
            LogUtils.e( "执行出错了",e);
            return null;
        }
    }

    public void beginTransaction(){
        //LogUtils.e("beginTransaction");
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public void setTransactionSuccessful(){
        //LogUtils.e("setTransactionSuccessful");
        try {
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public void endTransaction(){
        //LogUtils.e("endTransaction");
    }
}